"""
自定义身份认证后端，来实现多账号登陆
"""
from django.contrib.auth.backends import ModelBackend
from .models import User

class UsernameMobileAuthBackend(ModelBackend):

    # 重写authenticate实力方法，实现多账号登陆
    # 默认ModelBackend只会根据username过滤用户
    def authenticate(self, request, username=None, password=None, **kwargs):
        # request: 请求对象
        # username: 用户名或手机号
        # password: 密码

        # 1、根据用户名过滤
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            # 2、根据手机号过滤
            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist as e:
                return None

        # 3、其中某一个过滤出用户，再校验密码
        if user.check_password(password):
            return user